package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrBitString类
 * 实现位字符串数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrBitString implements AxdrType {
    private byte[] value = new byte[0];
    private int bitCount = 0;

    public AxdrBitString() {
    }

    public AxdrBitString(byte[] value, int bitCount) {
        this.value = value;
        this.bitCount = bitCount;
    }

    public byte[] getValue() {
        return value;
    }

    public int getBitCount() {
        return bitCount;
    }

    public void setValue(byte[] value, int bitCount) {
        this.value = value;
        this.bitCount = bitCount;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;
        
        // 解码位数
        AxdrUnsigned8 bitCountField = new AxdrUnsigned8();
        codeLength += bitCountField.decode(input);
        this.bitCount = bitCountField.getValue();
        
        // 计算字节数
        int byteCount = (this.bitCount + 7) / 8;
        
        // 解码位字符串内容
        this.value = new byte[byteCount];
        for (int i = 0; i < byteCount; i++) {
            this.value[i] = (byte) input.read();
        }
        
        return codeLength + byteCount;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength = 0;
        
        // 编码位数
        AxdrUnsigned8 bitCountField = new AxdrUnsigned8();
        bitCountField.setValue((short) this.bitCount);
        codeLength += bitCountField.encode(output);
        
        // 编码位字符串内容
        try {
            for (int i = 0; i < this.value.length; i++) {
                output.write(this.value[i]);
            }
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        
        return codeLength + this.value.length;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("BIT STRING {");
        for (int i = 0; i < this.bitCount; i++) {
            int byteIndex = i / 8;
            int bitIndex = 7 - (i % 8);
            int bit = (this.value[byteIndex] >> bitIndex) & 1;
            sb.append(bit);
        }
        sb.append("}");
        return sb.toString();
    }
}